package cn.hdustea.shopNavigation.ui.view.main

import android.content.Context
import android.content.Intent
import androidx.recyclerview.widget.LinearLayoutManager
import cn.hdustea.shopNavigation.R
import cn.hdustea.shopNavigation.adapter.FoodItemAdapter
import cn.hdustea.shopNavigation.config.ConstantUrl
import cn.hdustea.shopNavigation.entity.Food
import cn.hdustea.shopNavigation.ui.contract.FoodContract
import cn.hdustea.shopNavigation.ui.presenter.FoodPresenter
import com.bumptech.glide.Glide
import com.hdustea.base.base.BaseActivity
import com.hdustea.base.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.activity_food.*

class FoodActivity : BaseActivity<FoodContract.Presenter>(), FoodContract.View {
    private var foodAdapter: FoodItemAdapter? = null
    private var mCurrentPage: Int = 0

    companion object {

        fun startActivity(context: Context) {
            context.startActivity(Intent(context, FoodActivity::class.java))
        }

    }

    override fun initView() {
        Glide.with(this)
                .load("${ConstantUrl.BASE_URL}/image/banner/food1.jpg")
                .into(im_banner)
        val layoutManager = LinearLayoutManager(this)
        recycler_view.layoutManager = layoutManager
        showLoading()
    }

    override fun initData() {
        mPresenter?.getFoodList(0, false)
    }

    private fun initRecyclerView() {
        foodAdapter!!.animationEnable = true
        foodAdapter!!.loadMoreModule.loadMoreView = CustomLoadMoreView()
        foodAdapter!!.loadMoreModule.setOnLoadMoreListener {
            mPresenter?.getFoodList(mCurrentPage + 1, true)
        }
        foodAdapter!!.loadMoreModule.isAutoLoadMore = true
        //当自动加载开启，同时数据不满一屏时，是否继续执行自动加载更多(默认为true)
        foodAdapter!!.loadMoreModule.isEnableLoadMoreIfNotFullPage = false
    }

    override fun getLayoutRes(): Int = R.layout.activity_food

    override fun getPresenter(): FoodContract.Presenter = FoodPresenter(this)

    override fun setFoodList(foodList: MutableList<Food>, isRefresh: Boolean) {
        if (!isRefresh) {
            foodAdapter = FoodItemAdapter(R.layout.item_list_food, this)
            initRecyclerView()
            recycler_view.adapter = foodAdapter
            foodAdapter!!.setList(foodList)
        } else {
            if (foodList.isNotEmpty()) {
                mCurrentPage++
                foodAdapter?.addData(foodList)
                foodAdapter!!.loadMoreModule.loadMoreComplete()
            } else {
                foodAdapter!!.loadMoreModule.loadMoreEnd()
            }
        }
    }

    override fun onError() {
        foodAdapter!!.loadMoreModule.isEnableLoadMore = true
        foodAdapter!!.loadMoreModule.loadMoreFail()
    }
}